package top.forgirl.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.forgirl.domain.Company;
import top.forgirl.domain.Login;
import top.forgirl.domain.dto.CompanyDo;
import top.forgirl.mapper.CompanyMapper;
import top.forgirl.mapper.LoginMapper;
import top.forgirl.util.StringGenerateUtil;

import java.util.List;

@Service
public class CompanyService {

    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private LoginMapper loginMapper;

    public List<Company> listCompany() {

        return companyMapper.list();

    }

    public Company selectCompany(String cId) {

        return companyMapper.select(cId);
    }

    public Company deleteCompany(String cId) {

        Company company = selectCompany(cId);
        companyMapper.delete(company);
        loginMapper.delete(company.getRelation());

        return company;

    }

    public CompanyDo addCompany(CompanyDo companyDo) {
        String relation = StringGenerateUtil.generateUUID();
        String credential = StringGenerateUtil.generateCredential(8);
        Company company = new Company();
        Login login = new Login();

        company.setCId(companyDo.getCId());
        company.setRelation(relation);
        company.setContactNum(companyDo.getContactNum());
        company.setLocation(companyDo.getLocation());
        company.setName(companyDo.getName());

        login.setPrincipal(companyDo.getPrincipal());
        login.setCredential(credential);
        login.setLimit(relation);

        companyMapper.insert(company);
        loginMapper.insert(login);

        companyDo.setCredential(credential);
        return companyDo;
    }

    public Company updateCompany(Company company) {
        int result = companyMapper.update(company);
        if (result > 0) {
            return selectCompany(company.getCId());
        } else
            return null;
    }

    public Company selectCompanyByRelation(String relation) {
        return companyMapper.selectByRelation(relation);
    }
}
